import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams, TextInput, Content, Events } from 'ionic-angular';
import { EmojiProvider } from '../../providers/emoji/emoji';
import { ChatserviceProvider, ChartMessage } from '../../providers/chatservice/chatservice';
import { Storage } from '@ionic/storage';
import { RestProvider } from '../../providers/rest/rest';

// @IonicPage()
@Component({
  selector: 'page-chartdetails',
  templateUrl: 'chartdetails.html',
})
export class ChartdetailsPage {
  @ViewChild(Content) content: Content;
  @ViewChild('chatInput') messageInput: TextInput;
  chartUsername: any;
  chatUserId: string;
  userId: string;
  userName: string;
  userImgUrl: string;
  isOpenEmojipicker = false;
  errorMessage: any;
  editorMessage: string;
  messageList: ChartMessage[] = [];
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public emojis: EmojiProvider,
    public chartService: ChatserviceProvider,
    private storage: Storage,
    private rest: RestProvider,
    public event: Events) {
    this.chartUsername = this.navParams.get('username');
    this.chatUserId = this.navParams.get('userid');
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ChartdetailsPage');
  }
  ionViewDidEnter() {
    this.storage.get('UserId').then((val) => {
      if (val != null) {
        this.rest.getUserInfo(val)
          .subscribe(data => {
            this.userId = '140000198202211138';
            this.userName = data["UserNickName"];
            this.userImgUrl = data["UserHeadface"] + "?" + (new Date()).valueOf();
          })
      }
    });
    this.getMessages()
      .then(() => {
        this.scrollToBottom();
      });

    //听取消息的发布，订阅
    this.event.subscribe('chat.recevied', (msg, time) => {
      this.messageList.push(msg);
      this.scrollToBottom();
    })
  }
  /**
   * 调用 service 里面的方法进行属性的赋值
   * 
   * @returns 
   * @memberof ChartdetailsPage
   */
  getMessages() {
    return this.chartService.getMessageList()
      .then(res => {
        this.messageList = res;
      })
      .catch(error => {
        console.log(error);
      })
  }
  /**
   * 切换表情组件
   * 
   * @memberof ChartdetailsPage
   */
  switchEmojiPicker() {
    this.isOpenEmojipicker = !this.isOpenEmojipicker;
  }

  sendMessage(message) {
    if (!this.editorMessage.trim())
      return
    const id = Date.now().toString();
    let messageSend: ChartMessage = {
      messageId: id,
      userId: this.userId,
      username: this.userName,
      userImgUrl: this.userImgUrl,
      toUserId: this.chatUserId,
      time: Date.now(),
      message: this.editorMessage,
      status: 'pending'
    }
    this.messageList.push(messageSend);
    this.scrollToBottom();
    this.editorMessage = '';
    if (!this.isOpenEmojipicker) {
      this.messageInput.setFocus();
    }
    this.chartService.sendMessage(messageSend)
      .then(() => {
        let index = this.getMessageIndex(id);
        if (index !== -1) {
          this.messageList[index].status = 'sucess';
        }
      })
  }
  focus() {
    this.isOpenEmojipicker = false;
    this.content.resize();
    this.scrollToBottom();
  }

  ionViewWillLeave() {
    this.event.unsubscribe('chat.recevied');
  }
  getMessageIndex(id: string) {
    return this.messageList.findIndex(e => e.messageId === id);
  }
  scrollToBottom(): any {
    setTimeout(() => {
      if (this.content.scrollToBottom) {
        this.content.scrollToBottom();
      }
    }, 400);
  }
}
